package cn.kgc.controller;


import cn.kgc.pojo.Standard;
import cn.kgc.service.StandardService;
import cn.kgc.utils.PageInfo;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("standard")
public class StandardController {

    private  static Logger logger = Logger.getLogger(StandardController.class);

    @Resource
    StandardService standardService;


    @RequestMapping(value = "/limit")
    public String limit(@RequestParam(value = "currentPageNo",required = false) Integer currentPageNo,
                        @RequestParam(value = "pageSize",required = false) Integer pageSize,
                        @RequestParam(value = "zhname",required = false) String zhname,
                        Model model){

        PageInfo pageInfo = new PageInfo();
        if (currentPageNo !=null){
            pageInfo.setCurrentPageNo(currentPageNo);
        }
        if (pageSize!=null){
            pageInfo.setPageSize(pageSize);
        }
        int totalCount = standardService.getCount(zhname);
        pageInfo.setTotalConut(totalCount);
        List<Standard> list =standardService.getByPage(pageInfo.getCurrentPageNo(),pageInfo.getPageSize(),zhname);
        pageInfo.setData(list);
        model.addAttribute("standard12",pageInfo);
        return "standardLimit";
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(@RequestParam("id") Integer id,Model model){
        Standard standard = standardService.getStandardById(id);
        model.addAttribute("standard12",standard);
        return "standardUpdate";
    }

    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public String update(Standard standard){
        boolean flag = standardService.updateStandard(standard);
        if (flag){
            return "redirect:/standard/limit";
        }else {
            return "standardUpdate";
        }
    }



    @RequestMapping("/toAdd")
    public String toAdd(){
        return "standardAdd";
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(Standard standard,
                      HttpServletRequest request,
                      @RequestParam(value = "files",required = false) MultipartFile files){
        String idPicPath = null;
        if(!files.isEmpty()){
            String path = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
            logger.info("uploadFile path ============== > "+path);
            String oldFileName = files.getOriginalFilename();//原文件名
            logger.info("uploadFile oldFileName ============== > "+oldFileName);
            String prefix= FilenameUtils.getExtension(oldFileName);//原文件后缀
            logger.debug("uploadFile prefix============> " + prefix);
            int filesize = 500000;
            logger.debug("uploadFile size============> " + files.getSize());
            if(files.getSize() >  filesize){//上传大小不得超过 500k
                request.setAttribute("uploadFileError", " * 上传大小不得超过 500k");
                return "useradd";
            }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
                //生成一个不能重复的文件名称
                //当前时间戳+1000000以内的随机数+_Personal.jpg
                String fileName = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal.jpg";
                logger.debug("new fileName======== " + files.getName());
                File targetFile = new File(path, fileName);
                //判断当前路径文件夹是否存在，不存在则创建文件夹
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }
                //保存
                try {
                    files.transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    request.setAttribute("uploadFileError", " * 上传失败！");
                    return "useradd";
                }
                idPicPath = path+File.separator+fileName;
            }else{
                request.setAttribute("uploadFileError", " * 上传图片格式不正确");
                return "useradd";
            }
        }
        standard.setPackagePath(idPicPath);
        boolean flag = standardService.addStandard(standard);
        if (flag){
            return "redirect:/standard/limit";
        }else {
            return "standardAdd";
        }
    }

    @RequestMapping("/downLoad")
    public void downLoad(@RequestParam("id") Integer id,
                         HttpServletResponse response){
        logger.info("idPicPath==============="+id);
        String fileName = standardService.getStandardById(id).getPackagePath();

        try {
            InputStream is = new FileInputStream(new File(fileName));

            String filename = "下载文件.jpg";
            filename = URLEncoder.encode(filename,"UTF-8");

            response.addHeader("Content-Dispostion","attachment;filename="+filename);
            response.setContentType("multipart/form-data");
            BufferedOutputStream os = new BufferedOutputStream(response.getOutputStream());
            int len = 0;
            while ((len = is.read()) != -1){
                os.write(len);
                os.flush();
            }
            os.close();
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
        @RequestMapping("/toDel")
    public String toDel(@RequestParam("id")Integer id){
        boolean flag = standardService.delId(id);
        if (flag){
            return "redirect:/standard/limit";
        }else {
            return "standardLimit";
        }

    }


    @RequestMapping("/IsExist/{stdNum}")
    @ResponseBody
    public JSONObject IsExist(@PathVariable String stdNum) {

        Standard standard = standardService.getName(stdNum);
        JSONObject jsonObject = new JSONObject();
        if (standard == null) {
            jsonObject.put("code", "10000");
            jsonObject.put("msg", "可以使用");
        } else {
            jsonObject.put("code", "10001");
            jsonObject.put("msg", "不可以使用");
        }
        return jsonObject;
    }
}
